//
//  SYJRefreshControl.swift
//  weibo
//
//  Created by 孙英建 on 16/4/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// 保存状态的枚举
enum RefreshControlType: Int{
    // 正常状态
    case Normal = 0
    // 松手刷新
    case Pulling = 1
    // 正在刷新
    case Refreshing = 2
}


// 刷新控件的高度
private let RefreshHeight: CGFloat = 50

class SYJRefreshControl: UIControl {

    // 保存状态
    var status: RefreshControlType = RefreshControlType.Normal{
        didSet{
            switch status {
            case .Normal :
                messageLabel.text = "正常状态"
                
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= RefreshHeight
                    })
                }
                
            case .Pulling :
                messageLabel.text = "松手刷新"
                
            case .Refreshing :
                messageLabel.text = "正在刷新"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += RefreshHeight
                    }, completion: { (_) -> Void in
                        // 告诉外界要刷新了
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
   
            }
        }
    }

    
    
    var scrollView: UIScrollView?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK: - 供外界调用停止刷新
    func endRefreshing(){
        status = .Normal
    }
    
    // 设置UI
    func setUI(){
        self.backgroundColor = RGB(red: 55, green: 105, blue: 65)
        addSubview(messageLabel)
    }

    // 设置frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 当前控件
        self.frame = CGRectMake(0, -RefreshHeight, kWidth, RefreshHeight)
        
        // 提示label
        messageLabel.frame = CGRectMake(0, 0, kWidth, RefreshHeight)
    }
    
    
    // 监听添加到哪个控件上的方法
    override func willMoveToSuperview(newSuperview: UIView?) {
       
        if let scrollView = newSuperview as? UIScrollView {
            //scrollView.contentOffset.
            // 通过kvo 监听我们父控件的属性改变
            self.scrollView = scrollView
            
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
            
        }
    }
    
    // 监听我们那个对象的属性发生改变
    /*    
          - 正常状态 (没有松手)  contentOffset.y > -114   && 当前状态为pulling
          - 松手刷新 (没有松手)  contentOffset.y <= -114  && 当前状态为normal
          - 刷新中(已经松手)
          - 上一个状态 松手刷新
          - 必须还松手 
    */
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 获得临界值
        let contentMargin = -(RefreshHeight + scrollView!.contentInset.top)
       
        let contentOffsetY = scrollView?.contentOffset.y
        
        // 通过dragging 来判断我们是否在拖动scrollViewvb
        // - true 代表拖动中
        // - false 代表没有拖动
        if scrollView!.dragging {
            if contentOffsetY > contentMargin && status == RefreshControlType.Pulling {
                status = .Normal
            }else if contentOffsetY <= contentMargin && status == RefreshControlType.Normal {
                status = .Pulling
            }
            
        }else{
            if status == RefreshControlType.Pulling {
                status = .Refreshing
            }
        }
        
        
    }
    

    // MARK: - 懒加载控件o
    private lazy var messageLabel: UILabel = {
       let ml = UILabel()
        ml.font = UIFont.systemFontOfSize(14)
        ml.textColor = UIColor.whiteColor()
        ml.text = "正常状态"
        ml.textAlignment = NSTextAlignment.Center
        return ml
    }()
    
    // MARK: - 手动移除KVO
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}



















